import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/patrol/patrol_record_detail_data.dart';

import '../../net/response/patrol/patrol_record_list_data.dart';

class PatrolRecordDetailViewModel extends BaseListViewModel<PatrolRecordDetailData>{
  final PatrolRecordListData item;
  PatrolRecordDetailViewModel(BuildContext context,{required this.item}) : super(context);
  PatrolRecordModel _model = PatrolRecordModel();

  @override
  Future<List<PatrolRecordDetailData>> requestListData() async {
    return await _model.getDetailList(item.id!, page, pageLength);
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }


  Future<void> addSubmit(dynamic id) async {
    showLoadingDialog(msg: '提交中...');
    try{
      var data = await PostRequest.submitPatrol(id, "2", "",isSupplementaryCard: 1);
      hideDialog();
      showToast("补卡成功");
      requestRefresh();
    }catch(e){
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    // TODO: implement receiveMessage
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.REFRESH_PATROL){
      requestRefresh();
    }
  }
}

class PatrolRecordModel extends BaseMvvmModel{
  @override
  void onCleared() {
  }

  Future<List<PatrolRecordDetailData>> getDetailList(num id,int page,int rows) async {
    var map = <String,dynamic>{
      "id":id,
      "page":page,
      "rows":rows,
    };

    var jsonMap = {
      "jsonStr":jsonEncode(map),
      "page":page,
      "rows":rows,
    };

    var data = await HttpGo.instance.postData(PatrolApi.patrolRecordDetailList,data:jsonMap,options: PostRequest.urlencodedHeader);
    if('0'==data['code']){
      return ((data['data']['rows'] as List?) ?? []).map((e) => PatrolRecordDetailData.fromJson(e)).toList();
    }else{
      throw(data['msg']);
    }
  }
}